package com.mengdie.shuidi.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.utils.MDUtil;
import com.mengdie.shuidi.utils.webhelper.HHWebChromeClient;
import com.mengdie.shuidi.utils.webhelper.WVJBWebViewClient;
import com.orhanobut.logger.Logger;

import butterknife.Bind;
import butterknife.ButterKnife;


public class HtmlWebActivity extends BaseActivity implements HHWebChromeClient.OpenFileChooserCallBack{

    private static String TAG = "HtmlWebActivity";

    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.webView)
    WebView mWebView;
    @Bind(R.id.progress_bar)
    ProgressBar mProgressBar;

    private WVJBWebViewClient mWebViewClient;
    private String mCurUrl;

    public static Intent newIntent(String url) {
        Intent intent = new Intent();
        intent.setClass(AppContext.getInstance(), HtmlWebActivity.class);
        intent.putExtra(TAG, url);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_web_view);
        ButterKnife.bind(this);
        init();
        initWebView();
        getData();
    }

    private void init() {
        mTvGenericTitle.setText("套餐介绍");
        mRlGenericBack.setVisibility(View.GONE);
        mRlGenericBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView != null && mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    mRlGenericBack.setVisibility(View.GONE);
                }
            }
        });
    }

    @JavascriptInterface
    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true); // 允许执行js代码
        webSettings.setAllowFileAccess(true); // 可以访问文件
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        String ua = webSettings.getUserAgentString();
        webSettings.setUserAgentString(ua + "(MDAPP)");
        // 先加载网页再加载图片
        if (Build.VERSION.SDK_INT >= 19) {
            mWebView.getSettings().setLoadsImagesAutomatically(true);
        } else {
            mWebView.getSettings().setLoadsImagesAutomatically(false);
        }

        mWebViewClient = new MyWebViewClient(mWebView);

        mWebView.setWebViewClient(mWebViewClient);
        /**
         * 主要可以监听进度条的改变
         */
        mWebView.setWebChromeClient(new HHWebChromeClient(this) {
            @Override
            public void onProgressChanged(WebView view, int newProgress) { // 进度
                super.onProgressChanged(view, newProgress);
                if (newProgress > 95) {
//                    mProgressBar.setVisibility(View.GONE);
                }
            }
        });


    }

    @Override
    public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {

    }


    private class MyWebViewClient extends WVJBWebViewClient {
        public MyWebViewClient(WebView webView) {
            super(webView, new WVJBHandler() {
                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    String jsonString = data.toString();
                    MDUtil.webCall(HtmlWebActivity.this, jsonString);
                }
            });
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mCurUrl = url;
            Logger.d("url: " + url);
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
//            onWebLoadStart();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Logger.e(mWebView.getSettings().getUserAgentString());
//            onWebLoadFinished();
            if (mWebView.canGoBack()) {
                mRlGenericBack.setVisibility(View.VISIBLE);
            } else {
                mRlGenericBack.setVisibility(View.GONE);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description,
                                    String failingUrl) {
//            onWebLoadError();
        }
    }

    private void getData() {
        Intent intent = getIntent();
        mCurUrl = intent.getStringExtra(TAG);
        Logger.e("data  " + mCurUrl);
        if (!TextUtils.isEmpty(mCurUrl)) {
            mWebView.loadUrl(mCurUrl);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {  // goBack()表示返回WebView的上一页面
            mWebView.goBack();
            return true;
        } else {
            //结束当前页
            return super.onKeyDown(keyCode, event);
        }
    }
}
